<?php


namespace Ffzhou\HydrophisLogin\Extend;


use Swoole\Client;

class SwooleClient
{
    protected static $instance;  // 单例对象
    private $server;
    private $port;

    /**
     * 单例方法
     * @return self
     */
    public static function instance()
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 配置信息
     * @param $server 服务器
     * @param $port 端口号
     * @return $this
     */
    public function setConfig($server, $port) {
        $this->server = $server;
        $this->port = $port;
        return $this;
    }

    /**
     * 向Swoole服务器发送任务
     * @param int $type 任务类型
     * @param mixed $data 数据
     */
    public function publish($data) {
        try {
            $client = new Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
            $result = $client->connect($this->server, $this->port);
            if ($result) {
                return $client->send(json_encode($data));
            }
            else {
                return false;
            }
        }
        catch (\Exception $exception) {
            return false;
        }
    }

}
